package top.yuhaitao.core.service.impl;

import org.springframework.stereotype.Service;
import top.yuhaitao.core.pojo.ProductInfo;
import top.yuhaitao.core.repository.ProductInfoRepository;
import top.yuhaitao.core.service.SecondKillSevice;
import top.yuhaitao.core.util.RedisLock;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 秒杀
 */
@Service
public class SecondKillServiceImpl implements SecondKillSevice {
    private final static Long TIME_OUT = 5 * 1000L;

    private int count = 0;
    @Resource
    private RedisLock redisLock;
    @Resource
    private ProductInfoRepository productInfoRepository;

    @Override
    public ProductInfo querySeconedKillProductInfo(String productId) {
        Optional<ProductInfo> findById = productInfoRepository.findById(productId);
        return findById.orElse(new ProductInfo());
    }

    @Override
    public void seconedKill(String productId) {
        String time = String.valueOf(System.currentTimeMillis() + TIME_OUT);
        if (!redisLock.lock(productId, time)) {
            System.out.println("换个姿势，再来一次。");
            return;
        }
        ProductInfo productInfo = productInfoRepository.getOne(productId);
        if (productInfo.getProductStock() <= 0) {
            throw new RuntimeException("活动结束");
        } else {
            count++;
            //订单操作,积分操作，这里建议不要直接做db操作
            //用消息队列去做
            productInfo.setProductStock(productInfo.getProductStock() - 1);
            productInfoRepository.save(productInfo);
        }
        redisLock.unlock(productId, time);
    }
}
